# -*- coding: utf-8 -*-

# $Id: dja_skel.py 2 2012-09-01 15:54:17Z alexis.roda.villalonga@gmail.com $

from pkg_resources import iter_entry_points
from optparse import OptionParser
import locale
import os
import sys

def dja_skel():
    args, variables, options = _parse_args()
    if options.list_templates:
        _list_templates()
        return
    if options.list_variables:
        if not options.template:
            sys.stderr.write("--list-variables requires --template")
            return
        _list_variables(options.template)
        return
    if len(args) != 1:
        sys.stderr.write("Especify just one prjname.")
        return
    prjname = args[0]
    _instantiate(options.template, prjname, variables, options.encoding)

def _parse_args():
    """Parses the command line args.

    :raises:
    :returns: a tuple (options, vars, args)
    :rtype:
    """
    parser = OptionParser()
    parser.add_option("-e", "--encoding",
                      action="store",
                      default=locale.getpreferredencoding().lower(),
                      dest="encoding"
                      )
    parser.add_option("-l", "--list-templates",
                      action="store_true",
                      default=False,
                      dest="list_templates"
                      )
    parser.add_option("--list-variables",
                      action="store_true",
                      default=False,
                      dest="list_variables"
                      )
    parser.add_option("-t", "--template",
                      action="store",
                      dest="template"
                      )
    options, args = parser.parse_args()
    arg_vars = {}
    real_args = []
    for arg in args:
        if "=" in arg:
            name, value = arg.split("=", 1)
            arg_vars[name] = value
        else:
            real_args.append(arg)
    return (real_args, arg_vars, options)

def _list_templates():
    sys.stdout.write("List of available skeletons:\n")
    templates = []
    for entry_point in iter_entry_points("dja_skel.non_app_skeleton"):
        skeleton = entry_point.load()
        templates.append((entry_point.name, skeleton.summary))
    templates.sort()
    max_name_len = max( (len(n) for n, s in templates) )
    for name, summary in templates:
        sys.stdout.write("* {}: {}\n".format(
            name.ljust(max_name_len),
            summary
            ))

def _list_variables(template):
    for entry_point in iter_entry_points("dja_skel.non_app_skeleton", name=template):
        skeleton = entry_point.load()
        sys.stdout.write("List of variables '{}':\n".format(entry_point.name))
        for var in skeleton.variables:
            sys.stdout.write("  {}\n".format(var))

def _instantiate(template, prjname, variables, encoding):
    root = os.path.abspath(".")
    variables["prjname"] = prjname
    counter = 0
    for entry_point in iter_entry_points("dja_skel.non_app_skeleton", name=template):
        counter += 1
        skeleton_class = entry_point.load()
        skeleton = skeleton_class()
        skeleton.instantiate(root, variables, encoding=encoding)
    if not counter:
        sys.stderr.write("Template '%s' not found.\n" % template)
